package com.idbk.chargestation.activity.charge;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.R;
import com.idbk.chargestation.api.APIForCharge;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonChargeRefresh;
import com.idbk.chargestation.bean.JsonPileTariff;
import com.idbk.chargestation.bean.JsonPointPile;
import com.idbk.chargestation.bean.JsonQrScan;
import com.idbk.chargestation.dialog.DialogBill;
import com.idbk.chargestation.dialog.DialogResult;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.CheckUtil;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;

import java.util.Locale;

/**
 * 当前充电：交流充电桩（AC）
 *
 * @author zhx
 */

public class ActivityChargingAc extends BaseActivity implements OnClickListener {

    public final static String TAG = ActivityChargingAc.class.getSimpleName();
    /**
     * 操作：等待启动
     */
    public final static int CHARGE_ACTION_WAIT = 0;
    /**
     * 操作：已启动
     */
    public final static int CHARGE_ACTION_CHARGING = 1;
    /**
     * 数据刷新时间
     */
    public final static int ALTERNATE_DATA_REFRESH = 5000;
    /**
     * BMS电压参数 1：表示12V，交流充电桩只有12V
     */
    private final static int VOLTAGE_BNS_12 = 1;
    public final static String KEY_CHARGE_ACTION = "key_charge_action";
    public final static int REQUEST_CODE = 30376;

    private TextView mTexPerformance, mTexVoltage, mTexCurrent, mTexTitle, mTexChargeStyleTip, mTexUnit;
    private TextView mTexElectricity, mTexCost, mTexPrice, mTexTimePrice, mTexService, mTexChargeModel;
    private ImageView mImgLayer, mImgOuterRing, mImgInnerRing, mImgChargeBox;
    private TextView mTexChargeFull, mTexChargeCustom, mTexChargeStop;
    private JsonQrScan mPointInfor;
    private Handler mHandler;
    private String mPileSn, mGunNum;
    private ProgressDialog mPDialog;
    private JsonPileTariff mTariff;
    private int mLoseConnectionCount, mMaxLoseConnectionCount;
    private DialogResult mResultDialog;
    private DialogBill mBillDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_charging_ac);

        initView();

        initData();
    }

    public void initView() {
        initTextView();
        initImageView();
        initButton();
        initOnClickView();
    }

    private void initTextView() {
        mTexPerformance = (TextView) findViewById(R.id.performance);
        mTexVoltage = (TextView) findViewById(R.id.voltage);
        mTexCurrent = (TextView) findViewById(R.id.current);
        mTexTitle = (TextView) findViewById(R.id.title);
        mTexChargeStyleTip = (TextView) findViewById(R.id.tip);
        mTexUnit = (TextView) findViewById(R.id.unit);

        mTexElectricity = (TextView) findViewById(R.id.electricity);
        mTexCost = (TextView) findViewById(R.id.cost);
        mTexPrice = (TextView) findViewById(R.id.electricit_price);
        mTexService = (TextView) findViewById(R.id.service_price);
        mTexChargeModel = (TextView) findViewById(R.id.model);
        mTexTimePrice = (TextView) findViewById(R.id.show_price);
        if (mTexTimePrice != null) {
            mTexTimePrice.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        }
    }

    private void initImageView() {
        mImgOuterRing = (ImageView) findViewById(R.id.outer_ring);
        mImgInnerRing = (ImageView) findViewById(R.id.inner_ring);
        mImgLayer = (ImageView) findViewById(R.id.layer);
        mImgChargeBox = (ImageView) findViewById(R.id.charge_box);
    }

    private void initButton() {
        mTexChargeFull = (TextView) findViewById(R.id.automatic_full);
        mTexChargeCustom = (TextView) findViewById(R.id.custom_charge);
        mTexChargeStop = (TextView) findViewById(R.id.stop);
    }

    @SuppressWarnings("ConstantConditions")
    private void initOnClickView() {
        findViewById(R.id.toolbar_back).setOnClickListener(this);
        mTexTimePrice.setOnClickListener(this);
        mTexChargeFull.setOnClickListener(this);
        mTexChargeCustom.setOnClickListener(this);
        mTexChargeStop.setOnClickListener(this);
    }

    private void initData() {
        initLoseConnectionCount();
        mHandler = new Handler();
        judgeChargeState();
    }

    private void initLoseConnectionCount() {
        mLoseConnectionCount = 0;
        mMaxLoseConnectionCount = 4;
    }

    private void judgeChargeState() {
        int action = getIntent().getIntExtra(KEY_CHARGE_ACTION, -1);
        if (action == CHARGE_ACTION_CHARGING) {
            charging();
        } else if (action == CHARGE_ACTION_WAIT) {
            waitCharge();
        } else {
            Toast.makeText(this, "缺少必要的参数！", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void charging() {
        startCharge();
        mPileSn = getIntent().getStringExtra("pileSn");
        mTariff = getIntent().getParcelableExtra("tariff");
        mGunNum = String.format(Locale.CHINA, "%02d", getIntent().getIntExtra("gunNum", 1));
        mHandler.post(refreshThread);
    }

    public void startCharge() {
        Animation outerAnim = AnimationUtils.loadAnimation(ActivityChargingAc.this, R.anim.alternate_image_clockwise);
        Animation innerAnim = AnimationUtils.loadAnimation(ActivityChargingAc.this, R.anim.alternate_image_anticlockwise);
        Animation layerAnim = AnimationUtils.loadAnimation(ActivityChargingAc.this, R.anim.alternate_image_alpha);

        LinearInterpolator interpolator = new LinearInterpolator();
        outerAnim.setInterpolator(interpolator);
        innerAnim.setInterpolator(interpolator);
        layerAnim.setInterpolator(interpolator);

        mImgOuterRing.setImageDrawable(ContextCompat.getDrawable(ActivityChargingAc.this, R.drawable.ani_charging_box_outer_ring));
        mImgChargeBox.setImageDrawable(ContextCompat.getDrawable(ActivityChargingAc.this, R.drawable.bg_charging_box_ac_background_mask));
        mImgOuterRing.startAnimation(outerAnim);
        mImgInnerRing.startAnimation(innerAnim);
        mImgLayer.startAnimation(layerAnim);

        mTexTitle.setText("充电中");
        mTexChargeModel.setVisibility(View.VISIBLE);
        mTexChargeStop.setVisibility(View.VISIBLE);
        mTexChargeFull.setVisibility(View.GONE);
        mTexChargeCustom.setVisibility(View.GONE);
    }

    private void waitCharge() {
        mPointInfor = getIntent().getParcelableExtra(JsonQrScan.KEY);
        mTariff = mPointInfor.tariff;
        mGunNum = String.format(Locale.CHINA, "%02d", getIntent().getIntExtra("gunNum", 1));
        judgePileType(mPointInfor.pileType);
        mTexElectricity.setText(R.string.zero_decimals_two);
        mTexCost.setText(R.string.zero_decimals_two);
        mTexService.setText(mPointInfor.tariff.getServicePrice());
        String unit = mPointInfor.tariff.getServiceUnit();
        mTexUnit.setText(unit);
        //是否是分时电价
        if (mPointInfor.priceTypeEnum == JsonPointPile.PRICE_TYPE_TIME) {
            mTexTimePrice.setVisibility(View.VISIBLE);
        } else {
            mTexTimePrice.setVisibility(View.GONE);
        }
        String mTexCurrentPrice = mTariff.compareTime();
        mTexPrice.setText(mTexCurrentPrice);
        mPileSn = mPointInfor.pileSn;
    }

    //电桩类型的判断
    private void judgePileType(int type) {
        switch (type) {
            case JsonPointPile.PILE_TYPE_AC_SINGLE_PHASE:
                setPointTypeText("单相交流", "0.0", "0.00");
                break;
            case JsonPointPile.PILE_TYPE_AC_THREE_PHASE:
                setPointTypeText("三相交流", "0.0/0.0/0.0", "0.00/0.00/0.00");
                break;
            case JsonPointPile.PILE_TYPE_AC_DOUBLE_GUN_SINGLE_PHASE:
                setPointTypeText("单相交流" + "(枪" + mGunNum + ")", "0.0", "0.00");
                break;
            case JsonPointPile.PILE_TYPE_AC_DOUBLE_GUN_THREE_PHASE:
                setPointTypeText("三相交流" + "(枪" + mGunNum + ")", "0.0/0.0/0.0", "0.00/0.00/0.00");
                break;
            default:
                setPointTypeText("未知类型", "0.0", "0.00");
                break;

        }
    }

    private void setPointTypeText(String performance, String voltage, String current) {
        mTexPerformance.setText(performance);
        mTexVoltage.setText(voltage);
        mTexCurrent.setText(current);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            mHandler.removeCallbacks(refreshThread);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.show_price:
                showTimePrice();
                break;
            case R.id.automatic_full:
                showMyProgressDialog(true, false, "正在请求......");
                mMainRequest = APIForCharge.startCharge(mPileSn,
                        JsonPointPile.CHARGE_FINISH_BY_AUTO + "", null, mGunNum, VOLTAGE_BNS_12, mResponse);
                break;
            case R.id.toolbar_back:
                mHandler.removeCallbacks(refreshThread);
                finish();
                break;
            case R.id.custom_charge:
                Intent intent = new Intent(ActivityChargingAc.this, ActivityCustomCharge.class);
                intent.putExtra(JsonQrScan.KEY, mPointInfor);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.stop:
                mHandler.removeCallbacks(refreshThread);
                mPDialog = new ProgressDialog(this);
                mPDialog.setCancelable(false);
                mPDialog.setMessage("正在请求停止充电...");
                mPDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mMainRequest != null) {
                            mMainRequest.cancel();
                        }
                        mHandler.post(refreshThread);
                    }
                });
                mPDialog.show();
                mPDialog.setCanceledOnTouchOutside(false);
                mMainRequest = APIForCharge.stopCharge(mPileSn, mGunNum, mTexChargeStopResponse);
                break;
            default:
                break;
        }
    }

    public void showTimePrice() {
        if (mTariff != null) {
            View view = getLayoutInflater().inflate(R.layout.pop_pile_time_price, new LinearLayout(this), false);
            TextView textview = (TextView) view.findViewById(R.id.textview_pile_time_price);
            String str = mTariff.timePrices();
            textview.setText(CheckUtil.textFromHtml(str));
            view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
            int popupWidth = view.getMeasuredWidth();
            PopupWindow mPop = new PopupWindow(
                    view,
                    LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            mPop.setFocusable(true);
            mPop.setOutsideTouchable(true);
            // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
            mPop.setBackgroundDrawable(new PaintDrawable(Color.TRANSPARENT));

            int[] location = new int[2];
            mTexTimePrice.getLocationOnScreen(location);
            mPop.showAtLocation(
                    mTexTimePrice,
                    Gravity.NO_GRAVITY,
                    (location[0] + mTexTimePrice.getWidth() / 2) - popupWidth / 2,
                    location[1] + mTexTimePrice.getHeight());
        }
    }


    // 开始充电处理
    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonChargeRefresh result = GsonUtils.toBean(JsonChargeRefresh.class, response);
            if (result == null) {
                Toast.makeText(ActivityChargingAc.this, R.string.common_tip_rusultzero, Toast.LENGTH_SHORT).show();

            } else if (result.status == GlobalResult.OK.getStatus()) {
                startCharge();
                mTexChargeModel.setText(ActivityChargingDc.getChargeMethodSpan(result.chargeMethod, result.chargeLimit));
                mHandler.post(refreshThread);

            } else {
                Toast.makeText(ActivityChargingAc.this, result.message, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Log.d(TAG, error.getMessage(), error.getCause());
            //显示文字
            Toast.makeText(ActivityChargingAc.this, R.string.common_tip_resultnull, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEFinish() {
            dismissMyProgressDialog();
        }

    };

    /**
     * 刷新请求的结果
     */
    Runnable refreshThread = new Runnable() {

        @Override
        public void run() {

            APIForCharge.refreshCharge(mPileSn, mGunNum, new EHttpResponse() {

                @Override
                public void onEResponse(String response) {
                    JsonChargeRefresh refresh = GsonUtils.toBean(JsonChargeRefresh.class, response);
                    if (refresh == null) {
                        mTexChargeStyleTip.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                        mTexChargeStyleTip.setText("获取服务器数据为空");
                        mTexChargeStyleTip.setTextColor(Color.rgb(255, 0, 0));
                        mHandler.postDelayed(refreshThread, ALTERNATE_DATA_REFRESH);
                        //充电中，显示数据
                    } else if (refresh.status == GlobalResult.OK.getStatus()) {
                        if (refresh.getGunState() == JsonPointPile.STATUS_CHARGING) {
                            bindGunData(refresh);

                        } else if (refresh.getGunState() == JsonPointPile.STATUS_WAIT) {
                            mTexChargeStyleTip.setText("等待充电中");
                            mHandler.postDelayed(refreshThread, ALTERNATE_DATA_REFRESH);

                        } else if (refresh.getGunState() == JsonPointPile.STATUS_OFFLINE) {
                            if (mLoseConnectionCount >= mMaxLoseConnectionCount) {
                                stopState();
                                chargeStateDialog("充电提示", "桩无法与服务器通信，若要终止停电请按紧急停电按钮");

                            } else {
                                mLoseConnectionCount++;
                                mHandler.postDelayed(refreshThread, ALTERNATE_DATA_REFRESH);
                            }
                        } else {
                            stopState();
                            chargeStateDialog("充电结束", "稍后请到->我的钱包 查看账单");
                        }
                        //充电结束，显示账单
                    } else if (refresh.status == GlobalResult.CHARGE_FINISH_OK.getStatus()) {
                        stopState();
                        showBillDialog(refresh);
                        //充电结束，网络延迟，请到我的钱包查看
                    } else if (refresh.status == GlobalResult.CHARGE_FINISH_NETWORK.getStatus()) {
                        stopState();
                        chargeStateDialog("充电结束", "网络延迟,稍后请到->我的钱包 查看账单");
                        //登陆过期，请重新登陆
                    } else if (refresh.status == GlobalResult.TOKEN_INVALID.getStatus()
                            || refresh.status == GlobalResult.TOKEN_REQUIRED.getStatus()) {
                        jumpToLogin(ActivityChargingAc.this, true);

                    } else {
                        chargeStateDialog("充电提示", refresh.message);
                    }
                }

                @Override
                public void onEErrorResponse(VolleyError error) {
                    Log.d(TAG, error.getMessage(), error.getCause());
                    mTexChargeStyleTip.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                    mTexChargeStyleTip.setText("无法获取服务器数据，请检查当前网络");
                    mTexChargeStyleTip.setTextColor(Color.rgb(255, 0, 0));
                    mHandler.postDelayed(refreshThread, ALTERNATE_DATA_REFRESH);
                }

                @Override
                public void onEFinish() {
                    dismissMyProgressDialog();
                    //关闭 等待窗
                }
            });
        }
    };

    public void bindGunData(JsonChargeRefresh refresh) {
        mTexChargeStyleTip.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        mTexChargeStyleTip.setText("正在充电，已充 " + refresh.finishTime + " 分钟，充电完成后会通知您");
        mTexChargeStyleTip.setTextColor(ContextCompat.getColor(ActivityChargingAc.this, R.color.tj_text_content_6));

        // 桩类型及电流电压的处理
        if (refresh.pileType == JsonPointPile.PILE_TYPE_AC_SINGLE_PHASE) {
            mTexPerformance.setText("单相交流");
            mTexVoltage.setText(String.format(Locale.CHINA, "%.1f", refresh.voltage));
            mTexCurrent.setText(String.format(Locale.CHINA, "%.2f", refresh.current));

        } else if (refresh.pileType == JsonPointPile.PILE_TYPE_AC_THREE_PHASE) {
            mTexPerformance.setText("三相交流");
            mTexVoltage.setText(String.format(Locale.CHINA, "%.1f", refresh.voltage)
                    + "/" + String.format(Locale.CHINA, "%.1f", refresh.voltage_B)
                    + "/" + String.format(Locale.CHINA, "%.1f", refresh.voltage_C));

            mTexCurrent.setText(String.format(Locale.CHINA, "%.2f", refresh.current)
                    + "/" + String.format(Locale.CHINA, "%.2f", refresh.current_B)
                    + "/" + String.format(Locale.CHINA, "%.2f", refresh.current_C));

        } else if (refresh.pileType == JsonPointPile.PILE_TYPE_AC_DOUBLE_GUN_SINGLE_PHASE) {
            mTexPerformance.setText("单相交流" + "(枪" + refresh.gunNun + ")");
            mTexVoltage.setText(String.format(Locale.CHINA, "%.1f", refresh.voltage));
            mTexCurrent.setText(String.format(Locale.CHINA, "%.2f", refresh.current));

        } else if (refresh.pileType == JsonPointPile.PILE_TYPE_AC_DOUBLE_GUN_THREE_PHASE) {
            mTexPerformance.setText("三相交流" + "(枪" + refresh.gunNun + ")");
            mTexVoltage.setText(String.format(Locale.CHINA, "%.1f", refresh.voltage)
                    + "/" + String.format(Locale.CHINA, "%.1f", refresh.voltage_B)
                    + "/" + String.format(Locale.CHINA, "%.1f", refresh.voltage_C));

            mTexCurrent.setText(String.format(Locale.CHINA, "%.2f", refresh.current)
                    + "/" + String.format(Locale.CHINA, "%.2f", refresh.current_B)
                    + "/" + String.format(Locale.CHINA, "%.2f", refresh.current_C));
        } else {
            mTexPerformance.setText("未知");
            mTexVoltage.setText(String.format(Locale.CHINA, "%.1f", refresh.voltage));
            mTexCurrent.setText(String.format(Locale.CHINA, "%.2f", refresh.current));
        }

        // 是否显示分时电价
        if (refresh.priceTypeEnum == JsonPointPile.PRICE_TYPE_TIME) {
            mTexTimePrice.setVisibility(View.VISIBLE);
        } else {
            mTexTimePrice.setVisibility(View.GONE);
        }
        if (mTariff == null) {
            mTariff = refresh.tariff;
        }
        mTexElectricity.setText(String.format(Locale.CHINA, "%.2f", refresh.quantity));
        mTexCost.setText(String.format(Locale.CHINA, "%.2f", (refresh.chargeMoney + refresh.serverMoney)));
        mTexService.setText(refresh.tariff.getServicePrice());
        String unit = refresh.tariff.getServiceUnit();
        mTexUnit.setText(unit);
        mTexChargeModel.setText(ActivityChargingDc.getChargeMethodSpan(refresh.chargeMethod, refresh.chargeLimit));
        String mTexCurrentPrice = refresh.tariff.compareTime();
        mTexPrice.setText(mTexCurrentPrice);
        mHandler.postDelayed(refreshThread, ALTERNATE_DATA_REFRESH);
    }

    // 停止充电处理
    private final EHttpResponse mTexChargeStopResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonChargeRefresh stopResult = GsonUtils.toBean(JsonChargeRefresh.class, response);
            if (stopResult == null) {
                Toast.makeText(ActivityChargingAc.this, R.string.common_tip_rusultzero, Toast.LENGTH_SHORT).show();

            } else if (stopResult.status == GlobalResult.OK.getStatus()) {
                mPDialog.dismiss();
                stopState();
                //实时充电服务费用为serverMoney  停止充电服务费用为serviceMoney
                //这里serverMoney = serviceMoney是为了兼容showBillDialog无需重新再写
                stopResult.serverMoney = stopResult.serviceMoney;
                showBillDialog(stopResult);

            } else if (stopResult.status == GlobalResult.CHARGE_FINISH_NETWORK.getStatus()) {
                mPDialog.dismiss();
                stopState();
                chargeStateDialog("充电结束", "网络延迟,稍后请到->我的钱包 查看账单");

            } else if (stopResult.status == GlobalResult.CHARGE_FINISH_STOP.getStatus()) {
                mHandler.removeCallbacks(refreshThread);
                stopState();
                chargeStateDialog("充电结束", "充电已完成,请到->我的钱包 查看账单");

            } else {
                Toast.makeText(ActivityChargingAc.this, stopResult.message, Toast.LENGTH_SHORT).show();
                mHandler.post(refreshThread);
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Log.d(TAG, error.getMessage(), error.getCause());
            mPDialog.dismiss();
            Toast.makeText(ActivityChargingAc.this, R.string.common_tip_resultnull, Toast.LENGTH_SHORT).show();
            mHandler.post(refreshThread);
        }

        @Override
        public void onEFinish() {
            if (mPDialog != null) {
                mPDialog.dismiss();
            }
        }
    };


    public void stopState() {
        mImgOuterRing.clearAnimation();
        mImgInnerRing.clearAnimation();
        mImgLayer.clearAnimation();
        mImgOuterRing.setImageDrawable(ContextCompat.getDrawable(ActivityChargingAc.this, R.drawable.bg_charging_box_outer_ring));
        mImgChargeBox.setImageDrawable(ContextCompat.getDrawable(ActivityChargingAc.this, R.drawable.bg_charging_box_ac_background));
        mTexChargeModel.setVisibility(View.GONE);
        mTexChargeStop.setVisibility(View.GONE);
        mTexChargeFull.setVisibility(View.VISIBLE);
        mTexChargeCustom.setVisibility(View.VISIBLE);

        mTexTitle.setText("启动充电");
        if ("单相交流".equals(mTexPerformance.getText().toString())) {
            mTexVoltage.setText("0.0");
            mTexCurrent.setText(R.string.zero_decimals_two);

        } else if ("三相交流".equals(mTexPerformance.getText().toString())) {
            mTexVoltage.setText("0.0/0.0/0.0");
            mTexCurrent.setText(R.string.zero_zero_zero);

        } else {
            mTexVoltage.setText("0.0");
            mTexCurrent.setText(R.string.zero_decimals_two);
        }

        mTexElectricity.setText(R.string.zero_decimals_two);
        mTexCost.setText(R.string.zero_decimals_two);
        mTexChargeStyleTip.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(ActivityChargingAc.this, R.drawable.ico_charging_msg_tip), null, null, null);
        mTexChargeStyleTip.setText("已连接车辆，等待启动充电");
        mHandler.removeCallbacks(refreshThread);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //判断返回结果
        if (requestCode == REQUEST_CODE &&
                resultCode == RESULT_OK) {
            //取数据
            int mIntMethod = data.getIntExtra("mMethod", -1);
            int mIntLimit = data.getIntExtra("mSelect", -1);
            if (mIntMethod != -1 && mIntLimit != -1) {
                showMyProgressDialog(true, false, "正在请求中......");
                mMainRequest = APIForCharge.startCharge(mPileSn, mIntMethod + "", mIntLimit + "", mGunNum, VOLTAGE_BNS_12, mResponse);
            }
        }
    }

    private void chargeStateDialog(String mTexTitle, String msg) {
        if (isFinishing()) {
            return;
        }
        if (mBillDialog == null && mResultDialog == null) {
            mResultDialog = new DialogResult(ActivityChargingAc.this, true, mTexTitle, msg);
            mResultDialog.show();
            mResultDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (mBillDialog != null) {
                        mBillDialog.dismiss();
                    }
                    Intent intent = getIntent();
                    setResult(ActivityChargeList.RESPONSE_CODE, intent);
                    finish();
                }
            });
        }
    }

    public void showBillDialog(JsonChargeRefresh refresh) {
        if (isFinishing()) {
            return;
        }
        if (mResultDialog == null && mBillDialog == null) {
            mBillDialog = new DialogBill(ActivityChargingAc.this, refresh);
            mBillDialog.show();
            mBillDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (mResultDialog != null) {
                        mResultDialog.dismiss();
                    }
                    Intent intent = getIntent();
                    setResult(ActivityChargeList.RESPONSE_CODE, intent);
                    finish();
                }
            });
        }
    }

}
